package main

import (
	"log"
	"net/http"
	"runtime"
	"sort"
	"sync"
	"time"
)

func main() {
	log.Printf("cpu num =%d\n", runtime.NumCPU())
	//test3()
	//time.Sleep(5*time.Minute)
	c := ArrayScource(2, 25, 3, 45, 89, 100, 23, 324, 242)
	//for {
	//	if num, ok := <-c; ok {
	//		log.Println(num)
	//	}else{
	//		break
	//	}
	//}
	for v := range c {
		log.Printf("reve val <<<<=%+v", v)
	}
	//log.Println(c)
	//time.Sleep(time.Second*20)
	//chanint := InMemSort(c)
	//for v := range chanint {
	//	log.Printf("receive <<<<=%+v", v)
	//}

}
func InMemSort(a chan int) chan int {
	returnData := make(chan int)
	sli := []int{}
	go func() {
		for v := range a {
			sli = append(sli, v)
		}
		sort.Ints(sli)
		for _, val := range sli {
			returnData <- val
			log.Printf("send val >>>>=%+v", val)
		}
		close(returnData)
	}()
	return returnData
}
func ArrayScource(a ...int) chan int {
	out := make(chan int)
	go func() {
		for _, v := range a {
			time.Sleep(time.Second * 1)
			out <- v
			log.Printf("send val >>>>=%+v\n", v)

		}
		close(out)
	}()
	log.Println(">>>> finish ArraySOurce")
	return out
}

var wp sync.WaitGroup
var urls = []string{
	"http://www.baidu.com/",
	"http://www.360.com/",
	"http://www.qq.com/",
}

func test3() {
	for _, h := range urls {
		wp.Add(1)
		go func(url string) {
			defer wp.Done()
			log.Println(url)
			resp, err := http.Get(url)
			if err == nil {
				log.Printf("url=%v,status=%v", url, resp.Status)
			} else {
				log.Printf("err=", err)
			}
		}(h)

	}
	//wp.Wait()
}
func test2() {
	c := make(chan []int)
	go func(u chan []int) {
		sum := 0
		for i := 0; i < 10000; i++ {
			sum += i
		}
		log.Printf("sum =%d", sum)
		c <- []int{2}
	}(c)
	println("numGorountine =", runtime.NumGoroutine())
	<-c
}
func test1() {
	go func() {
		sum := 0
		for i := 1; i < 10000; i++ {
			sum = sum + i
		}
		log.Printf("sum = %d\n", sum)
	}()
	println("当前协程数numGoroutine =%d", runtime.NumGoroutine())
	select {
	case <-time.Tick(5 * time.Second):
		log.Println("5秒时间到")
	}
	println("before goMaxProces", runtime.GOMAXPROCS(0))
	//设置并发数目
	runtime.GOMAXPROCS(5)

	println("after goMaxProces", runtime.GOMAXPROCS(0))
}
